package com.qf.ticketdemo.controller;

import com.qf.ticketdemo.mapper.TicketMapper;
import com.qf.ticketdemo.pojo.Ticket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@RestController
//@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private TicketMapper ticketMapper;

    @Value("${winnum}")
    private String winnum;

    @GetMapping("/sell/{id}")
    public void sell(@PathVariable("id") Integer id) throws InterruptedException {

        while (true){
            //如果单机模式下， 是可以锁住的。但是机器一旦集群部署，不同机器中的id对象是不一样的，所以无法锁住
            //集群环境下，synchronized本地锁失效。此时我们需要使用分布式锁
            synchronized (id) {
                //先判断是否有票
                Ticket ticket = ticketMapper.selectById(id);
                Integer count = ticket.getCount();
                if (count > 0) {
                    //卖
                    System.out.println(winnum+"正在卖第" + count + "张票");

                    //模拟卖一张票耗时1s
                    Thread.sleep(1000);

                    //更新数据库
                    ticket.setCount(count - 1);
                    ticketMapper.updateById(ticket);
                } else {
                    break;
                }
            }
        }
    }
}
